package org.wx.io.mqtt;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.*;
import io.netty.handler.codec.mqtt.MqttDecoder;

import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.codec.mqtt.MqttMessage;


// 导入mqtt 的处理器
public class NettyMqttClient {

    private final String host; // 服务端地址

    private final int port; // 服务端端口号

    public NettyMqttClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 添加mqtt的编解码器
                    // 注意，在Netty4中它必须放在HttpServerCodec之前
                    ch.pipeline().addLast("decoder", new MqttDecoder())
                            .addLast("encoder", MqttEncoder.INSTANCE)
                            .addLast("handler", new MyMqttHandler());
                }
            });
            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        NettyMqttClient client = new NettyMqttClient("127.0.0.1", 1883);
        client.run();
    }
}
class MyMqttHandler extends SimpleChannelInboundHandler<Object> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("1233333333");
        if (msg instanceof MqttMessage) {
            System.out.println("客户端收到消息:" + msg);
        }
    }

}
